package com.hulman.oms.service;

import com.hulman.oms.bean.*;
import com.hulman.oms.dao.WorkTaskDao;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.DateUtil;
import com.hulman.oms.util.OrderUtil;
import com.hulman.oms.util.SubjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class WorkTaskService
{
    private static final String PROCESS_KEY = "work-task";

    @Autowired
    private WorkTaskDao workTaskDao;
    @Autowired
    private ProcInstService procInstService;
    @Autowired
    private TaskService taskService;

    public List<WorkTask> findWorkTasks(Map<String, Object> map)
    {
        return workTaskDao.findWorkTasks(map);
    }

    public Integer findWorkTasksCount(Map<String, Object> map)
    {
        return workTaskDao.findWorkTasksCount(map);
    }

    public Result findWorkTasksResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = workTaskDao.findWorkTasksCount(map);
        List<WorkTask> data = workTaskDao.findWorkTasks(map);
        return new Result(data, count);
    }

    public WorkTask findWorkTaskById(Integer id)
    {
        return workTaskDao.findWorkTaskById(id);
    }

    public void deleteWorkTaskById(Integer id)
    {
        workTaskDao.deleteWorkTaskById(id);
    }

    public void deleteWorkTasks(int[] ids)
    {
        workTaskDao.deleteWorkTasks(ids);
    }

    /**
     * 创建任务工单
     *
     * @param content 任务内容
     */
    @Transactional(rollbackFor = Exception.class)
    public Task create(String devices, String locations, String content)
    {
        User user = SubjectUtil.getUser();
        if (user == null)
        {
            throw new IoTException("用户未登陆");
        }
        //创建工单
        ProcInst procInst = procInstService.startProcess(PROCESS_KEY);
        WorkTask workTask = new WorkTask();
        workTask.setProcInstId(procInst.getId());
        workTask.setNo(OrderUtil.generate("RW"));
        workTask.setCreateById(user.getId());
        workTask.setCreateByName(user.getName());
        workTask.setDevices(devices);
        workTask.setLocations(locations);
        workTask.setContent(content);
        workTask.setCreateTime(new Date());
        workTask.setState(WorkTask.STATE_EXECUTING);
        workTaskDao.insertWorkTask(workTask);
        //创建任务
        Task createTask = new Task();
        createTask.setProcInstId(procInst.getId());
        createTask.setOwnerId(user.getId());
        createTask.setOwnerName(user.getName());
        createTask.setName(procInst.getStateName());
        createTask.setTag(PROCESS_KEY);
        createTask.setFormKey(workTask.getId().toString());
        createTask.addExtra("工单号", workTask.getNo());
        createTask.addExtra("任务内容", workTask.getContent());
        taskService.createAndCompleteTask(createTask);
        //完成工单
        procInst = procInstService.next(procInst.getId());
        Task completeTask = new Task();
        completeTask.setProcInstId(procInst.getId());
        completeTask.setOwnerId(user.getId());
        completeTask.setOwnerName(user.getName());
        completeTask.setName(procInst.getStateName());
        completeTask.setTag(PROCESS_KEY);
        completeTask.setFormKey(workTask.getId().toString());
        completeTask.addExtra("任务单号", workTask.getNo());
        completeTask.addExtra("任务内容", workTask.getContent());
        taskService.addTask(completeTask);
        completeTask.setPath("/pages/work-task/detail?taskId=" + completeTask.getId());
        completeTask.setPage("/work-task-info.html?taskId=" + completeTask.getId());
        taskService.saveTask(completeTask);
        return completeTask;
    }

    /**
     * 完成工单
     *
     * @param taskId     任务ID
     * @param id         任务工单ID
     * @param completion 完成情况
     */
    @Transactional(rollbackFor = Exception.class)
    public void complete(Integer taskId, Integer id, String completion)
    {
        //修改完善工单
        WorkTask workTask = workTaskDao.findWorkTaskById(id);
        workTask.setCompletion(completion);
        workTask.setCompleteTime(new Date());
        workTask.setState(WorkTask.STATE_DOCUMENTED);
        workTaskDao.updateWorkTask(workTask);
        //完成本次任务
        taskService.createAndCompleteTask(taskId);
    }

    /**
     * 撤销工单
     *
     * @param id 工单ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void terminate(Integer id)
    {
        //修改工单
        WorkTask workTask = workTaskDao.findWorkTaskById(id);
        workTask.setState(WorkTask.STATE_TERMINATED);
        workTaskDao.updateWorkTask(workTask);
        //终止流程
        procInstService.terminate(workTask.getProcInstId());
    }

    public List<WorkTask> findRecentWorkTasks(Integer count)
    {
        return workTaskDao.findRecentWorkTasks(count);
    }

    public Integer findTodayWorkTasksTotalCount()
    {
        return workTaskDao.findTodayWorkTasksTotalCount();
    }

    public List<NameValue> statDailyWorkTasks(Integer days)
    {
        return workTaskDao.statDailyWorkTasks(days);
    }

    public String getWorkTaskContents(Date date)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("startDate", DateUtil.toDate(date));
        map.put("endDate", DateUtil.toDate(date));
        List<WorkTask> workTasks = findWorkTasks(map);
        StringBuilder contentBuilder = new StringBuilder();
        for (int i = 0; i < workTasks.size(); i++)
        {
            WorkTask workTask = workTasks.get(i);
            contentBuilder.append(workTask.getContent() + "\n");
        }
        return contentBuilder.toString();
    }
}
